﻿$(function () {
    var $datagrid = $("#datagrid"), $toolbar = $("#toolbar"), $ticketType = $("#ticketType"), $title = $("#title"),
        $dialog = $("#dialog");
    $("#saveTicket").on("click", function () {
        openDialog();
    });
    $("#spotList").combobox({
        url: Constant.ctx('/mulanweb/admin/scenic_spot/search'),
        valueField: 'Id',
        textField: 'NameCn',
        editable: true,
        queryParams: {
            PageSize: 100,
            PageNumber: 1
        },
        loadFilter: function (data) {
            var result = [];
            var currentSize = data.PageSize;
            var totalSize = data.TotalRow;
            if (data.ReturnCode == 1 && currentSize >= totalSize) {
                if (data.DataList.length > 0) {
                    result.push({Id:0,NameCn:'全部景点'});
                    for (var tt = 0; tt < data.DataList.length; tt++) {
                        result.push({Id: data.DataList[tt].Id, NameCn: data.DataList[tt].ScenicName});
                    }
                }
            } else {
                Constant.showMessage("地点信息已超过最大值");
            }
            return result;
        },
        onChange: function (newV, oldV) {
            doSearch();
        }
    });
    $("#editTicket").on("click", function () {
        var rows = $datagrid.datagrid('getSelected');
        if (rows) {
            var targetId = rows.Id;
            openDialog("form-edit.jsp?targetId=" + targetId);
        } else {
            Constant.showMessage("请选择目标");
        }
    });
    $ticketType.combobox({
        onChange: function (v, o) {
            doSearch();
        }
    });
    
    var postImgNumber = 0;
    var selectImgNumber = 0;

    //保存主图
    function uploading(ticketId) {
        var files = document.getElementById('logoImage').files;
        selectImgNumber = selectImgNumber + files.length;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/save?targetId=' + ticketId + '&typeId=14'), "false");//typeId=13表示为门票券票logo图片
            xhr.send(fd);
            postImgNumber = postImgNumber + 1;
        }
        return true;
    }

    //保存轮播图
    function uploadings(ticketId) {
        var files = document.getElementById('fileImage').files;
        selectImgNumber = selectImgNumber + files.length;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=13'),'false');//typeId=13表示为门票券票图片
            xhr.send(fd);
            postImgNumber = postImgNumber + 1;
        }
    }

    //更新主图
    function uploading2(ticketId) {
        var files = document.getElementById('detail-logoImage').files;
        selectImgNumber = selectImgNumber + files.length;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=14'), "false");//typeId=14表示为门票券票logo图片
            xhr.send(fd);
            postImgNumber = postImgNumber + 1;
        }
    }

    //更新轮播图
    function uploadings2(ticketId) {
        var files = document.getElementById('detail-fileImage').files;
        selectImgNumber = selectImgNumber + files.length;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=13'), "false");
            //xhr.open('POST', Constant.toAbsoluteURL('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=13'));//typeId=13表示为门票券票图片
            /* * 如仍 出现 遗漏提交的问题，则使用如下方式同步提交
             xhr.open('POST', Constant.toAbsoluteURL('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=13'),"async=false||true");//typeId=13表示为门票券票图片*/
            xhr.send(fd);
            postImgNumber = postImgNumber + 1;
        }
    }

    function updateAccount() {
        $("form").form("submit", {
            url: $("form").attr("action"),
            onSubmit: function () {
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// hide progress bar while the form is invalid
                }
                return isValid;
            },
            success: function (respText) {
                var resp = $.parseJSON(respText);
                console.info(resp);
                if (resp.ReturnCode == 1) {
                    uploading2(resp.DataList.Data.Id);
                    uploadings2(resp.DataList.Data.Id);

                    var checkNumber = 0;
                    var checkQuery = function () {
                        setTimeout(function () {
                            if (postImgNumber == selectImgNumber) {
                                $dialog.dialog("close");
                                $("#datagrid").datagrid("reload");
                                Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                            } else {
                                if (checkNumber == 5) {
                                    Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                                } else {
                                    checkQuery();
                                }
                            }
                            checkNumber += 1;
                        }, 500);
                    }
                }
                checkQuery();
            }
        });
    }

    function saveAccount() {
        $("form").form("submit", {
            url: $("form").attr("action"),
            onSubmit: function () {
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// hide progress bar while the form is invalid
                }
                return isValid;
            },
            success: function (respText) {
                var resp = $.parseJSON(respText);
                Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                if (resp.ReturnCode == 1) {
                    uploading(resp.DataList.Data.Id);
                    uploadings(resp.DataList.Data.Id);

                    var checkNumber = 0;
                    var checkQuery = function () {
                        setTimeout(function () {
                            if (postImgNumber == selectImgNumber) {
                                $dialog.dialog("close");
                                $("#datagrid").datagrid("reload");
                                Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                            } else {
                                if (checkNumber == 5) {
                                    Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                                } else {
                                    checkQuery();
                                }
                            }
                            checkNumber += 1;
                        }, 500);
                    }
                    checkQuery();
                }
            }
        });
    }

    function openDialog(editPath) {
        $dialog.dialog({
            title: editPath ? "编辑内容" : "新增内容",
            width: 500,
            height: 500,
            closed: false,
            cache: false,
            href: editPath || 'form.jsp',
            modal: true,
            onClose: function () {
                $("#form-dialog").dialog("destroy");
                $("#detail-logoImage").val("");
                $("#detail-fileImage").val("");
                $(".upload_delete").click();
                $("#detail-preview").html("");
            },
            buttons: [{
                text: '保存',
                handler: editPath ? updateAccount : saveAccount
            }]
        });
    }

    $datagrid.datagrid({
        singleSelect: true,
        fit: true,
        border: false,
        fitColumns: true,
        url: Constant.ctx("/mulanweb/admin/ticket/search"),
        method: 'post',
        pagination: true,
        toolbar: $toolbar,
        columns: [[
            {field: 'Id', title: '编号'},
            {field: 'Title', title: '标题'},
            {field: 'SpotName', title: '景点名'},
            {field: 'SellerName', title: '商家名'},
            {field: 'OldNzdPrice', title: '原价($)'},
            {field: 'Price', title: '现价(￥)'},
            {
                field: 'Sales', title: '剩余(卖出)', formatter: function (v, r, i) {
                var total = r.Total - r.SurplusTotal;
                return r.SurplusTotal + "(" + total + ")";
            }
            },
            {field: 'SaveAdminName', title: '新增者'},
            {field: 'UpdateAdminName', title: '最后修改者'},
            {field: 'CreateTime', title: '创建时间'},
            {
                field: 'BasicCommodity', title: '基本商品', formatter: function (v, r, i) {
                var html = '';
                if (v == 0) {
                    html = html + '否,<a href="#" onclick="basicCommodity(' + r.Id + ')">设为基本</a>';
                } else {
                    html = html + '<div style="width:2px;height:10px;background:red"></div>是,<a href="#" onclick="basicCommodity(' + r.Id + ')">取消基本</a>';
                }
                return html;
            }
            },
            {
                field: 'HotCommodity', title: '操作', formatter: function (v, r, i) {
                var html = '';
                if (v == 0) {
                    html = html + '<a href="#" onclick="saveHot(' + r.Id + ',23)">设为爆款</a>';
                } else if (v == 1) {
                    html = html + '<a href="#" onclick="saveHot(' + r.Id + ',23)">取消爆款</a>';
                }
                if (!r.DeleteTime) {
                    html = html + '  <a href="#" onclick="deleteContent(' + r.Id + ',23)">删除</a>'
                }
                return html;
            }
            }
        ]],
        onBeforeLoad: function (param) {
            param.PageNumber = param.page;
            param.PageSize = param.rows;

            var typeId = $ticketType.combo("getValue");
            if (typeId && typeId != 0) {
                param.typeId = typeId;
            }
            var title = $title.val();
            if (title) {
                param.title = title;
            }

            var ticketId = $("#ticketId").val();
            if(ticketId){
                param.ticketId = ticketId;
            }

            var spotId = $("#spotList").combo('getValue');
            if(spotId && spotId !=0){
                param.spotId = spotId;
            }

            var sellerName = $("#sellerName").val();
            if(sellerName){
                param.sellerName = sellerName;
            }

            console.info(sellerName);
            return true;
        },
        loadFilter: function (data) {
            var newData = {};
            if (data.ReturnCode == 1) {
                newData.rows = data.DataList;
                if (newData.rows.length > 0) {
                    newData.total = data.TotalRow;
                } else {
                    newData.total = 0;
                }
            }
            return newData;
        },
        onDblClickRow: function (index, rows) {
            showDetail(rows);
        }
    });
    function showDetail(row) {
        $.post(Constant.ctx("/mulanweb/admin/ticket/getDetail"), {targetId: row.Id}, function (info) {
            var module = $("#detail").html();
            var compileModule = Template7.compile(module);
            var resultModule = compileModule(info.target);
            $("#dialogDetail").html(resultModule);
        })
        $("#dialogDetail").dialog({
            title: '详情',
            width: 400,
            height: 450,
            inline:true,
        });
    }
});
function doSearch() {
    $("#datagrid").datagrid("reload");
}
function basicCommodity(targetId) {
    if (targetId) {
        $.post(Constant.ctx("/mulanweb/admin/ticket/basicCommodity"), {targetId: targetId}, function (info) {
            if (info.ReturnCode == 1) {
                Constant.showMessage(info.AlertMessage,info.message,"操作成功");
                $("#datagrid").datagrid("reload");
            } else {
                Constant.showMessage(info.message, "操作失败");
            }
        })
    }
}